//
// Created by hamlet on 2022/1/14.
//

#include "player.h"
#include <utility>
#include <QApplication>
#include <QRandomGenerator64>

PlayerInfo::PlayerInfo(QString name, QString intro, const QColor &color, qint64 id) :
        Message(Message::Type::PlayerInfo), m_name(qMove(name)), m_intro(qMove(intro)), m_snakeColor(color), m_ID(id) {
    if (m_name.isEmpty())
        m_name = QApplication::tr("匿名");
    if (m_intro.isEmpty())
        m_intro = QApplication::tr("这个人没有填简介啊~~~");
}

PlayerInfo *PlayerInfo::parseJson(const QJsonObject &json) {
    return new PlayerInfo{json["name"].toString(), json["intro"].toString(), json["color"].toString(),
                          json["id"].toInteger()};
}

QJsonObject PlayerInfo::toJson() const {
    return {{"type",  static_cast<int>(Message::Type::PlayerInfo)},
            {"id",    m_ID},
            {"name",  m_name},
            {"intro", m_intro},
            {"color", QString("#%1%2%3").arg(m_snakeColor.red(), 2, 16)
                              .arg(m_snakeColor.green(), 2, 16)
                              .arg(m_snakeColor.blue(), 2, 16)}};
}

inline QString hexDisplay(qint64 num) {
    QString output;
    auto p = (char8_t *) &num;
    for (int i = 0; i < 8; ++i) {
        char8_t digit = p[i] >> 4;
        output.append(QChar((digit < 10 ? '0' : '7') + digit));
        digit = p[i] - (digit << 4);
        output.append(QChar((digit < 10 ? '0' : '7') + digit));
    }
    return qMove(output);
}

QString PlayerInfo::simpleInfo() const {
    return qMove(QString("%1 %2 %3").arg(hexDisplay(m_ID), m_name, m_intro));
}

void PlayerInfo::generateRandomID() {
    m_ID = static_cast<qint64>(QRandomGenerator64::global()->generate64());
}

void PlayerInfo::setSnakeColorRGB(int r, int g, int b) {
    m_snakeColor.setRgb(r, g, b);
}
